<?php 

if (!defined('__TYPECHO_ROOT_DIR__')) exit; 
require_once __DIR__ . '/IpLocator.php';


date_default_timezone_set('Asia/Shanghai');
//error_log("Firewall: Current blacklist: " . print_r($blacklist, true));


$options = Typecho_Widget::widget('Widget_Options');
$user = Typecho_Widget::widget('Widget_User');
$request = Typecho_Request::getInstance();
$response = Typecho_Response::getInstance();

// 检查管理员权限
if (!$user->pass('administrator')) {
    throw new Typecho_Exception('无权访问', 403);
}

// 处理表单动作
$notice = null;
if ($request->isPost()) {
    if ($request->get('action') == 'add') {
        $ip = trim($request->get('ip'));
        // 修改为直接调用函数（非类方法）
        if (filter_var($ip, FILTER_VALIDATE_IP) || isValidWildcardIP($ip)) {
            TypechoFirewall_Plugin::addToBlacklist($ip, '手动添加');
            $notice = ['message' => 'IP规则已添加: ' . $ip, 'type' => 'success'];
        } else {
            $notice = ['message' => '无效的IP地址或格式（允许使用通配符*）', 'type' => 'error'];
        }
    } elseif ($request->get('action') == 'remove') {
        $ip = $request->get('ip');
        TypechoFirewall_Plugin::removeFromBlacklist($ip);
        $notice = array('message' => 'IP已从黑名单移除: ' . $ip, 'type' => 'success');
    } elseif ($request->get('action') == 'clear_logs') {
        file_put_contents(TypechoFirewall_Plugin::BLOCKED_LOG, '');
        file_put_contents(TypechoFirewall_Plugin::LOG_FILE, '');
        $notice = array('message' => '日志已清空', 'type' => 'success');

    }elseif ($request->get('action') == 'add_white') {
        $ip = trim($request->get('ip'));
        if (filter_var($ip, FILTER_VALIDATE_IP) || isValidWildcardIP($ip)) {
            TypechoFirewall_Plugin::addToWhitelist($ip, '手动添加');
            $notice = ['message' => 'IP已添加到白名单: ' . $ip, 'type' => 'success'];
        } else {
            $notice = ['message' => '无效的IP地址或格式', 'type' => 'error'];
        }
    } elseif ($request->get('action') == 'remove_white') {
        $ip = $request->get('ip');
        TypechoFirewall_Plugin::removeFromWhitelist($ip);
        $notice = ['message' => 'IP已从白名单移除: ' . $ip, 'type' => 'success'];
    }
}


/**
 * 验证带通配符的IP格式
 * 例如：192.168.* 或 192.168.5.*
 */
function isValidWildcardIP($ip) {
    // 去除空格并转小写（兼容性处理）
    $ip = strtolower(trim($ip));
    
    // 基本格式检查（允许1-4段，且只能包含数字和*）
    if (!preg_match('/^(\d{1,3}|\*)(\.(\d{1,3}|\*)){0,3}$/', $ip)) {
        return false;
    }
    
    // 补全缺失的段为通配符（如将"192.*"补全为"192.*.*.*"）
    $segmentCount = substr_count($ip, '.') + 1;
    for ($i = $segmentCount; $i < 4; $i++) {
        $ip .= '.*';
    }
    
    // 分割验证每段
    $segments = explode('.', $ip);
    foreach ($segments as $segment) {
        if ($segment !== '*' && ($segment < 0 || $segment > 255)) {
            return false;
        }
    }
    
    // 通配符只能出现在最后1-2段（安全限制）
    $firstWildcardPos = array_search('*', $segments);
    if ($firstWildcardPos !== false && $firstWildcardPos < (count($segments) - 2)) {
        return false;
    }
    
    return true;
}


// 获取数据
$blacklist = TypechoFirewall_Plugin::getBlacklist();
$whitelist = TypechoFirewall_Plugin::getWhitelist();
$lastBlocked = TypechoFirewall_Plugin::getLastBlocked();
$blockedLogs = file_exists(TypechoFirewall_Plugin::BLOCKED_LOG) ? 
    array_slice(file(TypechoFirewall_Plugin::BLOCKED_LOG), -20) : array();
$accessLogs = file_exists(TypechoFirewall_Plugin::LOG_FILE) ? 
    array_slice(file(TypechoFirewall_Plugin::LOG_FILE), -20) : array();


include 'header.php';
include 'menu.php';
?>

<?php
// 处理AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_request'])) {
    $offset = intval($_POST['current_offset'] ?? 10);
    $batchSize = 10;
    
    $moreData = parseAccessLogs($accessLogs, $batchSize, $offset);
    
    foreach ($moreData['items'] as $item) {
        echo '<tr>';
        echo '<td class="font-monospace">'. htmlspecialchars($item['ip']) .'</td>';
        echo '<td>'. $item['location'] .'</td>';
        echo '<td class="text-end">'. $item['count'] .'</td>';
        echo '</tr>';
    }
    
    $remaining = $moreData['total'] - $offset - $batchSize;
    
    if ($remaining > 0) {
        echo '<div class="text-center py-3 border-top" id="loadMoreBtnContainer">
                <button type="button" id="loadMoreBtn" class="btn btn-sm btn-outline-primary"
                        data-total="'. $moreData['total'] .'"
                        data-processed="'. $moreData['processed'] .'">
                    <i class="bi bi-chevron-down me-1"></i>
                    加载更多 (还有 '. $remaining .' 条记录)
                </button>
              </div>';
    }
    
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>防火墙管理 - <?php $options->title(); ?></title>
    <meta charset="<?php $options->charset(); ?>">
    <link rel="stylesheet" href="<?php $options->adminStaticUrl('css', 'normalize.css'); ?>">
    <link rel="stylesheet" href="<?php $options->adminStaticUrl('css', 'grid.css'); ?>">
    <link rel="stylesheet" href="<?php $options->adminStaticUrl('css', 'style.css'); ?>">
    <link href="https://fastly.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://fastly.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">

    <style>
    .firewall-container { margin: 20px 0; }
    .firewall-panel { 
        background: #fff; 
        border-radius: 3px; 
        box-shadow: 0 1px 3px rgba(0,0,0,.1); 
        margin-bottom: 30px; 
    }
    .firewall-header { padding: 15px; border-bottom: 1px solid #eee; }
    .firewall-body { padding: 15px; }
    .firewall-footer { padding: 15px; border-top: 1px solid #eee; text-align: right; }
    .firewall-table { width: 100%; border-collapse: collapse; }
    .firewall-table th, .firewall-table td { padding: 8px 12px; border: 1px solid #eee; }
    .firewall-table th { background: #f5f5f5; text-align: left; }
    .firewall-log { max-height: 300px; overflow-y: auto; background: #fafafa; padding: 10px; border: 1px solid #ddd; }
    .firewall-log pre { margin: 0; font-family: monospace; white-space: pre-wrap; }
    .btn { display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; line-height: 1.4; text-align: center; cursor: pointer; border: 1px solid transparent; border-radius: 4px; }
    .btn-danger { color: #fff; background-color: #d9534f; border-color: #d43f3a; }
    .btn-primary { color: #fff; background-color: #337ab7; border-color: #2e6da4; }
    .btn-xs { padding: 1px 5px; font-size: 12px; line-height: 1.5; border-radius: 3px; }
    .text-error { color: #a94442; }
    .text-success { color: #3c763d; }
    
    /* 新增布局样式 */
    .typecho-page-main {
        padding: 0 20px;
        max-width: 1200px;
        margin: 0 auto;
    }
    
    /* 响应式调整 */
    @media (max-width: 767px) {
        .typecho-page-main {
            padding: 0 15px;
        }
        .firewall-panel {
            margin-bottom: 20px;
        }
    }


    /***日志显示***/
    .firewall-log-text pre {
    white-space: pre-wrap;
    word-wrap: break-word;
    margin: 0;
    font-family: var(--bs-font-monospace);
    font-size: 14px;
}
.table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}
.text-truncate {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
@media (max-width: 767.98px) {
    .card-header h5 {
        font-size: 1.1rem;
    }
    .table td, .table th {
        padding: 0.5rem;
        font-size: 0.85rem;
    }
    .table-responsive {
        padding-right: 1px; /* 防止滚动条遮挡 */
    }
}


.font-monospace {
    font-family: var(--bs-font-monospace);
}
.card-header h5 {
    font-weight: 600;
}
.table code {
    color: #d63384;
    background-color: rgba(214,51,132,.1);
    padding: 2px 4px;
    border-radius: 4px;
}
.alert pre {
    white-space: pre-wrap;
    word-wrap: break-word;
    margin: 0;
}
@media (max-width: 768px) {
    .card-body .row > .col {
        margin-bottom: 15px;
    }
    .card-body .row > .col:last-child {
        margin-bottom: 0;
    }
}
</style>
</head>
<body>
<div class="typecho-page-main">
    <div class="container-fluid mt-4 mb-4">
    <div class="d-flex justify-content-between align-items-center">
        <h2 class="fw-bold mb-0">
            <i class="bi bi-shield-lock me-2"></i>
            网站防火墙管理
        </h2>
        <!-- 这里可以添加右侧操作按钮（可选） -->
        <div class="btn-group">
            <button class="btn btn-sm btn-outline-secondary">
                <i class="bi bi-question-circle"></i> 帮助
            </button>
        </div>
    </div>
    <hr class="mt-2 mb-3">
</div>


    <div class="firewall-container">
        <?php if (!empty($notice)): ?>
    <div class="container-fluid mt-3" id="message">
        <div class="alert alert-<?php echo $notice['type'] === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
            <i class="bi <?php echo $notice['type'] === 'success' ? 'bi-check-circle-fill' : 'bi-exclamation-triangle-fill'; ?> me-2"></i>
            <?php echo $notice['message']; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    </div>
<?php endif; ?>


        <!--ip黑名单管理-->
        <div class="container-fluid mt-3">
    <!-- 网站防火墙状态面板 -->
    <div class="card mb-4 shadow-sm">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="bi bi-shield-lock me-2"></i>网站防火墙状态</h5>
        </div>
        <div class="card-body">
            <div class="row row-cols-1 row-cols-md-3 g-4">
                <div class="col">
                    <div class="card h-100 border-primary">
                        <div class="card-body text-center">
                            <h6 class="card-subtitle mb-2 text-muted">黑名单IP数量</h6>
                            <h3 class="card-title text-primary"><?php echo count($blacklist); ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col">
                    <div class="card h-100 border-success">
                        <div class="card-body text-center">
                        <h6 class="card-subtitle mb-2 text-muted">白名单IP数量</h6>
                        <h3 class="card-title text-success"><?php echo count(TypechoFirewall_Plugin::getWhitelist()); ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col">
                    <div class="card h-100 border-danger">
                        <div class="card-body text-center">
                            <h6 class="card-subtitle mb-2 text-muted">已拦截攻击次数</h6>
                            <h3 class="card-title text-danger"><?php echo $lastBlocked['count']; ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col">
                    <div class="card h-100 border-warning">
                        <div class="card-body">
                            <h6 class="card-subtitle mb-2 text-muted">最后拦截记录</h6>
                            <div class="alert alert-warning p-2 mb-0">
                                <pre class="mb-0 font-monospace small"><?php echo htmlspecialchars($lastBlocked['last']); ?></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 简易IP访问统计表格 -->
<div class="card mb-4">
    <div class="card-header bg-light d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-activity me-2"></i>IP访问统计</h5>
        <small class="text-muted">仅显示TOP 10</small>
    </div>
    <div class="card-body p-0">
        <form id="loadMoreForm" method="post">
            <input type="hidden" name="current_offset" value="10">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>IP地址</th>
                            <th>IP属地</th>
                            <th class="text-end">总访问次数</th>
                        </tr>
                    </thead>
                    <tbody id="ipStatsBody">
                        <?php
                        // 解析日志的函数
                        function parseAccessLogs($logs, $limit = 10, $offset = 0) {
                            $ipCounts = [];
                            $processed = 0;
                            
                            foreach ($logs as $log) {
                                if (preg_match('/\] (\S+)/', $log, $matches)) {
                                    $ip = trim($matches[1]);
                                    if (filter_var($ip, FILTER_VALIDATE_IP)) {
                                        $ipCounts[$ip] = ($ipCounts[$ip] ?? 0) + 1;
                                    }
                                }
                                
                                // 安全限制
                                if ($processed++ > 10000) break;
                            }
                            
                            arsort($ipCounts);
                            $results = [];
                            $index = 0;
                            
                            foreach ($ipCounts as $ip => $count) {
                                if ($index++ < $offset) continue;
                                if (count($results) >= $limit) break;
                                
                                $results[] = [
                                    'ip' => $ip,
                                    'location' => VisitorInfo_IpLocator::queryLocation($ip),
                                    'count' => number_format($count)
                                ];
                            }
                            
                            return [
                                'items' => $results,
                                'total' => count($ipCounts),
                                'processed' => $processed
                            ];
                        }
                        
                        // 初始加载
                        $initialData = parseAccessLogs($accessLogs, 10, 0);
                        
                        foreach ($initialData['items'] as $item) {
                            echo '<tr>';
                            echo '<td class="font-monospace">'. htmlspecialchars($item['ip']) .'</td>';
                            echo '<td>'. $item['location'] .'</td>';
                            echo '<td class="text-end">'. $item['count'] .'</td>';
                            echo '</tr>';
                        }
                        ?>
                    </tbody>
                </table>
                
                <?php if ($initialData['total'] > 10): ?>
                <div class="text-center py-3 border-top">
                    <button type="button" id="loadMoreBtn" class="btn btn-sm btn-outline-primary"
                            data-total="<?= $initialData['total'] ?>"
                            data-processed="<?= $initialData['processed'] ?>">
                        <i class="bi bi-chevron-down me-1"></i>
                        加载更多 (还有 <?= $initialData['total'] - 10 ?> 条记录)
                    </button>
                </div>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>


    </div>


    <!-- IP黑名单管理面板 -->
    <div class="card mb-4 shadow-sm">
        <div class="card-header bg-danger text-white">
            <h5 class="mb-0"><i class="bi bi-ban me-2"></i>IP黑名单管理</h5>
        </div>
        <div class="card-body">
            <!-- 添加IP表单 -->
            <form method="post" class="mb-4">
                <div class="row g-2">
                    <div class="col-md-8 col-12">
                        <div class="input-group">
                            <span class="input-group-text"><i class="bi bi-ip"></i></span>
                            <input type="text" name="ip" class="form-control" placeholder="输入要屏蔽的IP地址，例如: 192.168.1.100，支持通配符，如192.168.3*/192.168.*">
                        </div>
                    </div>
                    <div class="col-md-4 col-12">
                        <input type="hidden" name="action" value="add">
                        <button type="submit" class="btn btn-danger w-100">
                            <i class="bi bi-plus-circle me-1"></i>添加到黑名单
                        </button>
                    </div>
                </div>
            </form>
            <!-- 黑名单列表 -->
            <h4 class="mb-3"><i class="bi bi-list-check me-2"></i>当前黑名单列表</h4>
            <?php if (!empty($blacklist)): ?>
                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th width="70%">IP地址</th>
                                <th width="30%" class="text-end">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($blacklist as $ip): ?>
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <span class="badge bg-danger me-2"><i class="bi bi-x-circle"></i></span>
                                        <code><?php echo htmlspecialchars($ip); ?></code>
                                    </div>
                                </td>
                                <td class="text-end">
                                    <form method="post" class="d-inline" action="<?php echo $options->adminUrl('extending.php?panel=TypechoFirewall%2Fmanage.php'); ?>">
                                        <input type="hidden" name="action" value="remove">
                                        <input type="hidden" name="ip" value="<?php echo htmlspecialchars($ip); ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定要移除此IP吗？')">
                                            <i class="bi bi-trash"></i> 移除
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="alert alert-info">
                    <i class="bi bi-info-circle me-2"></i>当前没有IP在黑名单中
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- 白名单管理面板 -->
<div class="card mb-4 shadow-sm">
    <div class="card-header bg-success text-white">
        <h5 class="mb-0"><i class="bi bi-check-circle me-2"></i>IP白名单管理</h5>
    </div>
    <div class="card-body">
        <!-- 添加IP表单 -->
        <form method="post" class="mb-4">
            <div class="row g-2">
                <div class="col-md-8 col-12">
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-ip"></i></span>
                        <input type="text" name="ip" class="form-control" placeholder="输入要信任的IP地址，支持通配符，如192.168.*">
                    </div>
                </div>
                <div class="col-md-4 col-12">
                    <input type="hidden" name="action" value="add_white">
                    <button type="submit" class="btn btn-success w-100">
                        <i class="bi bi-plus-circle me-1"></i>添加到白名单
                    </button>
                </div>
            </div>
        </form>
        
        <!-- 白名单列表 -->
        <h4 class="mb-3"><i class="bi bi-list-check me-2"></i>当前白名单列表</h4>
        <?php $whitelist = TypechoFirewall_Plugin::getWhitelist(); ?>
        <?php if (!empty($whitelist)): ?>
            <div class="table-responsive">
                <table class="table table-striped table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th width="70%">IP地址</th>
                            <th width="30%" class="text-end">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($whitelist as $ip): ?>
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <span class="badge bg-success me-2"><i class="bi bi-check-circle"></i></span>
                                    <code><?php echo htmlspecialchars($ip); ?></code>
                                </div>
                            </td>
                            <td class="text-end">
                                <form method="post" class="d-inline">
                                    <input type="hidden" name="action" value="remove_white">
                                    <input type="hidden" name="ip" value="<?php echo htmlspecialchars($ip); ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定要移除此IP吗？')">
                                        <i class="bi bi-trash"></i> 移除
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="alert alert-info">
                <i class="bi bi-info-circle me-2"></i>当前没有IP在白名单中
            </div>
        <?php endif; ?>
    </div>
</div>


<!--日志-->
       <div class="container-fluid mt-3">
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center bg-light">
            <h5 class="mb-0">拦截日志 (最近20条)</h5>
            <div class="btn-group btn-group-sm">
                <button class="btn btn-outline-primary active view-toggle" data-log-type="blocked" data-view="text">
                    <i class="bi bi-file-text"></i> 文本视图
                </button>
                <button class="btn btn-outline-primary view-toggle" data-log-type="blocked" data-view="table">
                    <i class="bi bi-table"></i> 表格视图
                </button>
            </div>
        </div>
        <div class="card-body p-0">
            <?php if (!empty($blockedLogs)): ?>
                <!-- 文本视图 -->
                <div class="firewall-log-text p-3" data-log-type="blocked">
                    <pre class="mb-0"><?php echo htmlspecialchars(implode("", $blockedLogs)); ?></pre>
                </div>
                
                <!-- 表格视图 -->
                <div class="firewall-log-table table-responsive" data-log-type="blocked" style="display: none;">
                    <table class="table table-sm table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th style="width: 50px;">#</th>
                                <th>日期时间</th>
                                <th>IP地址</th>
                                <th>状态</th>
                                <th>类型</th>
                                <th>URI</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($blockedLogs as $index => $log): 
                                preg_match('/\[(.*?)\] \[(.*?)\] \[(.*?)\] (.*?): .*? \| URI: (.*)/', $log, $matches);
                                if (count($matches) >= 6):
                            ?>
                                <tr>
                                    <td class="text-center text-muted"><?php echo $index + 1; ?></td>
                                    <td><?php echo htmlspecialchars($matches[1]); ?></td>
                                    <td><?php echo htmlspecialchars($matches[2]); ?></td>
                                    <td><span class="badge bg-danger"><?php echo htmlspecialchars($matches[3]); ?></span></td>
                                    <td><?php echo htmlspecialchars($matches[4]); ?></td>
                                    <td class="text-truncate" style="max-width: 150px;" title="<?php echo htmlspecialchars($matches[5]); ?>"><?php echo htmlspecialchars($matches[5]); ?></td>
                                </tr>
                            <?php endif; endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="p-3 text-muted">暂无拦截日志</div>
            <?php endif; ?>
        </div>
        <div class="card-footer bg-light">
            <form method="post" class="mb-0">
                <input type="hidden" name="action" value="clear_logs">
                <button type="submit" class="btn btn-sm btn-danger">
                    <i class="bi bi-trash"></i> 清空日志
                </button>
            </form>
        </div>
    </div>
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center bg-light">
            <h5 class="mb-0">访问日志 (最近20条)</h5>
            <div class="btn-group btn-group-sm">
                <button class="btn btn-outline-primary active view-toggle" data-log-type="access" data-view="text">
                    <i class="bi bi-file-text"></i> 文本视图
                </button>
                <button class="btn btn-outline-primary view-toggle" data-log-type="access" data-view="table">
                    <i class="bi bi-table"></i> 表格视图
                </button>
            </div>
        </div>
        <div class="card-body p-0">
            <?php if (!empty($accessLogs)): ?>
                <!-- 文本视图 -->
                <div class="firewall-log-text p-3" data-log-type="access">
                    <pre class="mb-0"><?php echo htmlspecialchars(implode("", $accessLogs)); ?></pre>
                </div>
                
                <!-- 表格视图 -->
                <div class="firewall-log-table table-responsive" data-log-type="access" style="display: none;">
                    <table class="table table-sm table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th style="width: 50px;">#</th>
                                <th>日期时间</th>
                                <th>IP地址</th>
                                <th>IP属地</th>
                                <th>方法</th>
                                <th>URI</th>
                                <th>User Agent</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($accessLogs as $index => $log): 
                                preg_match('/\[(.*?)\] (.*?) (GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH) (.*?) "(.*)"/', $log, $matches);
                                if (count($matches) >= 6):
                            ?>
                                <tr>
                                    <td class="text-center text-muted"><?php echo $index + 1; ?></td>
                                    <td><?php echo htmlspecialchars($matches[1]); ?></td>
                                    <td><?php echo htmlspecialchars($matches[2]); ?></td>
                                    <td><?= $matches[2] ? VisitorInfo_IpLocator::queryLocation(htmlspecialchars($matches[2])) : '未知' ?></td>
                                    <td><span class="badge bg-primary"><?php echo htmlspecialchars($matches[3]); ?></span></td>
                                    <td class="text-truncate" style="max-width: 120px;" title="<?php echo htmlspecialchars($matches[4]); ?>"><?php echo htmlspecialchars($matches[4]); ?></td>
                                    <td class="text-truncate" style="max-width: 150px;" title="<?php echo htmlspecialchars($matches[5]); ?>"><?php echo htmlspecialchars($matches[5]); ?></td>
                                </tr>
                            <?php endif; endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="p-3 text-muted">暂无访问日志</div>
            <?php endif; ?>
        </div>
    </div>
</div>

    <div class="firewall-panel">
    <div class="firewall-header">
        <h3>日志状态</h3>
    </div>
    <div class="firewall-body">
        <p>白名单文件: 
            <?php 
            $whiteFile = TypechoFirewall_Plugin::WHITELIST_FILE;
            if (file_exists($whiteFile)) {
                echo '已启用，最后修改: ' . date('Y-m-d H:i:s', filemtime($whiteFile));
            } else {
                echo '<span class="text-error">未创建或不可写</span>';
            }
            ?>
        </p>
        <p>访问日志: 
            <?php 
            $logFile = TypechoFirewall_Plugin::LOG_FILE;
            if (file_exists($logFile)) {
                echo '已启用，最后写入: ' . date('Y-m-d H:i:s', filemtime($logFile));
                echo ' (大小: ' . round(filesize($logFile)/1024, 2) . 'KB)';
            } else {
                echo '<span class="text-error">未创建或不可写</span>';
            }
            ?>
        </p>
        <p>拦截日志: 
            <?php 
            $blockedFile = TypechoFirewall_Plugin::BLOCKED_LOG;
            if (file_exists($blockedFile)) {
                echo '已启用，最后写入: ' . date('Y-m-d H:i:s', filemtime($blockedFile));
            } else {
                echo '<span class="text-error">未创建或不可写</span>';
            }
            ?>
        </p>
        <?php if (!is_writable(dirname(TypechoFirewall_Plugin::LOG_FILE))): ?>
            <p class="text-error">警告: 日志目录不可写，请检查目录权限</p>
        <?php endif; ?>
    </div>
</div>
</div>

    <script>
        setTimeout(() => {
            const message = document.getElementById('message');
            if (message) {
                message.style.opacity = '0';
                setTimeout(() => message.remove(), 500); // 淡出动画后彻底移除
            }
        }, 5000); // 5秒后触发


        //日志显示
        document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.view-toggle').forEach(button => {
        button.addEventListener('click', function() {
            const logType = this.dataset.logType;
            const view = this.dataset.view;
            
            // 切换按钮样式
            document.querySelectorAll(`.view-toggle[data-log-type="${logType}"]`).forEach(btn => {
                btn.classList.remove('active');
            });
            this.classList.add('active');
            
            // 切换视图
            document.querySelector(`.firewall-log-text[data-log-type="${logType}"]`).style.display = 
                view === 'text' ? 'block' : 'none';
            document.querySelector(`.firewall-log-table[data-log-type="${logType}"]`).style.display = 
                view === 'table' ? 'block' : 'none';
        });
    });
});


//新增
document.getElementById('loadMoreBtn')?.addEventListener('click', function() {
    const btn = this;
    const form = document.getElementById('loadMoreForm');
    const offsetInput = form.current_offset;
    const offset = parseInt(offsetInput.value);
    const batchSize = 10;
    
    btn.disabled = true;
    btn.innerHTML = `<span class="spinner-border spinner-border-sm me-1"></span>加载中...`;
    
    // 创建FormData对象
    const formData = new FormData(form);
    formData.append('ajax_request', '1');
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(html => {
        // 从返回的HTML中提取新内容
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const newRows = doc.getElementById('ipStatsBody')?.innerHTML;
        const newBtn = doc.getElementById('loadMoreBtn');
        
        if (newRows) {
            document.getElementById('ipStatsBody').innerHTML += newRows;
            offsetInput.value = offset + batchSize;
            
            if (newBtn) {
                btn.outerHTML = newBtn.outerHTML;
            } else {
                btn.parentElement.remove();
            }
        }
    })
    .catch(() => {
        btn.innerHTML = '加载失败，点击重试';
        btn.disabled = false;
    });
});
    </script>

</body>
</html>

<?php
require_once __DIR__ . '/check.php';
include 'copyright.php';
include 'common-js.php';
include 'table-js.php';
include 'footer.php';
?>